package com.njupt.backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/12/13 9:13
 * @Description: 39. 组合总和
 * @Version: 1.0
 */


public class CombinationSum {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        List<List<Integer>> results = new ArrayList<>();
        List<Integer> result = new LinkedList<>();
        int startIndex = 0;
        int sum = 0;
        trackBacking(startIndex,candidates,target,results,result,sum);
        return results;


    }

    private void trackBacking(int startIndex, int[] candidates, int target, List<List<Integer>> results, List<Integer> result,int sum) {

        if(sum == target){
            results.add(new ArrayList(result));
            return;
        } else if (sum > target) {
            return;
        }

        for (int i = startIndex; i <candidates.length ; i++) {
            sum += candidates[i];
            result.add(candidates[i]);
            trackBacking(i,candidates,target,results,result,sum);
            sum -= candidates[i];
            result.remove(result.size()-1);
        }

    }

    public static void main(String[] args) {
        int[] candidates = {2,3,5};
        CombinationSum test = new CombinationSum();
        List<List<Integer>> lists = test.combinationSum(candidates, 8);
        System.out.println(lists);
    }
}
